<template>
	<a-spin :spinning="uploadLoading">
		<a-upload-dragger style="padding: 4em 0" :show-upload-list="false" :custom-request="uploadRequest" @change="handleChange">
			<p class="ant-upload-drag-icon">
				<inbox-outlined></inbox-outlined>
			</p>
			<p class="ant-upload-text">单击或拖动文件到此区域进行上传</p>
			<p class="ant-upload-hint">仅支持单个上传</p>
			<p class="ant-upload-hint">如果存在商品同步失败，请查看下方表格原因</p>
		</a-upload-dragger>
	</a-spin>
	<a-card title="同步结果" class="mt-4">
		<a-table ref="table" bordered class="ant-table-striped" :row-class-name="(_record, index) => (index % 2 === 1 ? 'table-striped' : null)" :columns="columns" :data-source="dataSource">
		</a-table>
	</a-card>
</template>

<script setup name="miniappGoodBatchCreate">
	import fileApi from "@/api/dev/fileApi";
	const emit = defineEmits({ successful: null })
	import { message } from 'ant-design-vue'
	import platformApi from "@/api/platform/platformApi";
	const uploadLoading = ref(false)
	const table = ref(null)
	const dataSource = ref([])

	const columns = [
		{
			title: '商品编码',
			dataIndex: 'goodCode',
			width: 120
		},
		{
			title: '商品名称',
			dataIndex: 'goodName',
			width: 300
		},
		{
			title: '导入结果',
			dataIndex: 'error'
		}
	]

	// 上传本地文件
	// const uploadRequest = (data) => {
	// 	const fileData = new FormData()
	// 	fileData.append('file', data.file)
	// 	bizRewardUserApi
	// 		.upload(fileData)
	// 		.then(() => {
	// 			message.success('上传成功')
	// 			table.value.refresh(true)
	// 		})
	// 		.finally(() => {
	// 			if (hideLoading) {
	// 				setTimeout(hideLoading)
	// 			}
	// 		})
	// }

	let hideLoading

	// 上传本地文件
	const uploadRequest = (data) => {
		uploadLoading.value = true
		const fileData = new FormData()
		fileData.append('file', data.file)
		platformApi.batchCreateItem(fileData)
			.then((res) => {
				message.success('上传成功')
				emit('successful')
				if (hideLoading) {
					setTimeout(hideLoading)
				}
				dataSource.value = res.map(r => Object.assign(r, r.data ))
				if (dataSource.value.length === 0) {
					dataSource.value.push({
						goodCode: "",
						goodName: "全部商品",
						error: "导入成功"
					})
				}
				console.log(dataSource.value)
			})
			.finally(() => {
				uploadLoading.value = false
			})
	}


	const handleChange = (info) => {
		if (info.file.status !== 'uploading') {
			console.log(info.file, info.fileList);
		}
		if (info.file.status === 'uploading' && !hideLoading) {
			hideLoading = message.loading('上传中，请勿关闭当前页面', 0)
		}
		if (info.file.status === 'done') {
			setTimeout(hideLoading)
			message.success(`${info.file.name} file uploaded successfully`);
		} else if (info.file.status === 'error') {
			setTimeout(hideLoading)
			message.error(`${info.file.name} file upload failed.`);
		}
		console.log(info.file)
	};

</script>

<style scoped>
.ant-table-striped :deep(.table-striped) td {
	background-color: #fafafa;
}
</style>
